<?php


namespace KukePay\Ali\Payment\Auth;


use KukePay\Ali\Payment\Kernel\ConfigFactory;
use KukePay\Ali\Payment\Unifiedorder\Application;

class Factory
{
    private $config;

    private $method = 'alipay.system.oauth.token';

    private $scope = 'auth_base';

    private $grant_type = 'authorization_code';

    public function __construct(ConfigFactory $config)
    {
        $this->config = $config;
    }

    /**
     * @param $scope
     * @return $this
     */
    public function setScope($scope)
    {
        $this->scope = $scope;
        return $this;
    }


    /**
     * 获取授权地址
     * @param string $redirect
     * @return string
     */
    public function redirect(string $redirect)
    {
        return 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=' . $this->config->getAppId() . '&redirect_uri=' . "$redirect" . '&scope=' . $this->scope . '&state=123456';
    }

    /**
     * 获取token
     * @param $auth_code
     * @return string
     * @throws \KukePay\ExceptionHandler
     */
    public function getAccessToken($auth_code)
    {
        $extend = [
            'grant_type' => $this->grant_type,
            'code' => $auth_code
        ];
        return Application::getInterface($this->config)->set([], $this->method, $extend)->send();
    }

    /**
     * 获取用户信息
     * @param $token
     * @return string
     * @throws \KukePay\ExceptionHandler
     */
    public function getUserInfo($token)
    {
        $method = 'alipay.user.info.share';

        return Application::getInterface($this->config)->getUser($method, [
            'auth_token' => $token
        ])->send();
    }

    /**
     * 拼接签名字符串
     * @param array $urlObj
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if ($k != "sign") $buff .= $k . "=" . $v . "&";
        }
        $buff = trim($buff, "&");
        return $buff;
    }

}